package com.lm.caffeine.example;

import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class AsyncCacheExample {
    public static void main(String[] args) {
        // 创建异步缓存实例
        AsyncLoadingCache<String, String> asyncCache = Caffeine.newBuilder()
                .expireAfterWrite(5, TimeUnit.MINUTES) // 写入后 5 分钟过期
                .refreshAfterWrite(2, TimeUnit.MINUTES) // 写入后 2 分钟刷新
                .buildAsync(key -> loadDataFromDatabase(key)); // 异步加载

        // 异步获取缓存
        asyncCache.get("user:1").thenAccept(value -> System.out.println("缓存值: " + value));

        // 主线程等待
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private static String loadDataFromDatabase(String key) {
        System.out.println("加载数据库数据 for key: " + key);
        return "UserData:" + key;
    }
}
